package com.saint.swipemenulistview.http;

import android.content.Context;
import android.widget.Toast;

import org.xutils.BuildConfig;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.logging.LogManager;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * Created by Administrator on 2017/11/4.
 */

public class NetWorkUtils {
    private static SSLContext mSSLContext = null;
    private static final String TAG = "NetWorkUtils";
    public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000;

    /**
     * http get请求
     *
     * @param params   请求参数 get请求使用 addQueryStringParameter方法添加参数
     * @param callback 回调对象
     */
    public static Callback.Cancelable getHttpRequest(RequestParams params, final HttpCallback callback) {
        return sendHttpRequest(HttpMethod.GET, params, callback);
    }

    /**
     * http post请求
     *
     * @param params   请求参数 post请求使用 addBodyParameter方法添加参数
     * @param callback 回调对象
     */
    public static Callback.Cancelable postHttpRequest(RequestParams params, final HttpCallback callback) {
        return sendHttpRequest(HttpMethod.POST, params, callback);
    }


    public static Callback.Cancelable sendHttpRequest(HttpMethod method, RequestParams params, final HttpCallback callback) {

        if (params == null) {
            params = new RequestParams();
        }

        params.setCacheMaxAge(1000 * 0); //为请求添加缓存时间
        params.setConnectTimeout(DEFAULT_CACHE_EXPIRY_TIME);
        final String url = params.getUri();

//        LogUtil.d("sendRequest: url = " + url);
//        SSLContext sslContext = getSSLContext(GoPlusApplication.getApplication());
//        if (null == sslContext) {
//            if (BuildConfig.DEBUG) LogManager.d(TAG, "Error:Can't Get SSLContext!");
//            return null;
//        }

//        params.setSslSocketFactory(sslContext.getSocketFactory());

        return x.http().request(method, params, new Callback.CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException msg) {
//                Toast.makeText(text, msg.getMessage(), Toast.LENGTH_SHORT).show();
//                callback.onFinished();
            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
//                Toast.makeText(text, arg0.getMessage(), Toast.LENGTH_SHORT).show();
//                LogManager.i(TAG, "==> RequestCallBack.onError()");
//                LogManager.e(TAG, "==> response：" + arg0.getMessage() + "\n==> error：" + arg1);
//                callback.onFinished();
            }

            @Override
            public void onSuccess(String result) {
//                LogManager.i(TAG, "==> RequestCallBack.onSuccess()");
                if (result == null) {
                    return;
                }
//                callback.onSuccess(result);
            }

            @Override
            public void onFinished() {
//                LogUtil.d("onFinished");
            }
        });
    }

    /**
     * 获取Https的证书
     *
     * @param context 上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
        CertificateFactory certificateFactory = null;
        InputStream inputStream = null;
        Certificate cer = null;
        KeyStore keystore = null;
        TrustManagerFactory trustManagerFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            inputStream = context.getAssets().open("baidu.cer");//这里导入SSL证书文件
            try {
                cer = certificateFactory.generateCertificate(inputStream);
//                LogManager.i(TAG, cer.getPublicKey().toString());
            } finally {
                inputStream.close();
            }

            //创建一个证书库，并将证书导入证书库
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null); //双向验证时使用
            keystore.setCertificateEntry("trust", cer);

            // 实例化信任库
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);

            mSSLContext = SSLContext.getInstance("TLS");
            mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            //信任所有证书 （官方不推荐使用）
//         s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
//
//              @Override
//              public X509Certificate[] getAcceptedIssuers() {
//                  return null;
//              }
//
//              @Override
//              public void checkServerTrusted(X509Certificate[] arg0, String arg1)
//                      throws CertificateException {
//
//              }
//
//              @Override
//              public void checkClientTrusted(X509Certificate[] arg0, String arg1)
//                      throws CertificateException {
//
//              }
//          }}, new SecureRandom());

            return mSSLContext;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

abstract class HttpCallback {
    public abstract void onSucc(String result);

    public abstract void onfailed();
}

